package com.wjerp.tplus.server.api.controller;

import com.wjerp.tplus.server.api.controller.base.BaseController;
import com.wjerp.tplus.server.api.request.ModifyPasswordRequest;
import com.wjerp.tplus.server.common.exception.BusinessException;
import com.wjerp.tplus.server.common.model.LoginUserDetailInfo;
import com.wjerp.tplus.server.common.security.JwtUser;
import com.wjerp.tplus.server.domain.service.UserInfoService;
import com.wjerp.tplus.server.common.model.BaseResponseData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author lishuailei
 */
@Api(tags="用户信息相关api")
@RestController
@RequestMapping("user")
public class UserController extends BaseController {

    @Resource
    private UserInfoService userInfoService;

    @ApiOperation("获取账户用户信息")
    @GetMapping
    public ResponseEntity<BaseResponseData> getUserDetailInfo() {
        try{
            Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if(obj.toString().equals("anonymousUser")){
                return fail("","用户未登陆，请登陆",null);
            }
            JwtUser authentication = (JwtUser) obj;
            LoginUserDetailInfo userDetailInfo= userInfoService.getUserDetailInfo(authentication.getDisplayUserId());
            userDetailInfo.setCompanyCode(authentication.getCompanyCode());
            List<String> roles=new ArrayList<>();
            Iterator iterator= authentication.getAuthorities().iterator();
            while (iterator.hasNext()){
                roles.add(iterator.next().toString());
            }
            userDetailInfo.setRoles(roles);
            return success(userDetailInfo);
        }catch(BusinessException e){
            return fail(e.getErrorCode(), e.getErrorMsg(), null);
        }
    }

    @ApiOperation("修改密码")
    @PostMapping("modifyPassword")
    public ResponseEntity<BaseResponseData> modifyPassword(
            @RequestBody  ModifyPasswordRequest modifyPasswordRequest){
        try {
            modifyPasswordRequest.checkParams();
            JwtUser authentication = (JwtUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            userInfoService.modifyPassword(authentication.getDisplayUserId(),modifyPasswordRequest.getPassword());
            return success(true);
        }catch (BusinessException e) {
            e.printStackTrace();
            return fail(e.getErrorCode(), e.getErrorMsg(), e.getCause());
        }
    }

}